//
//  SearchViewController.m
//  SuperRadio
//
//  Created by Damon on 14/12/17.
//  Copyright (c) 2014年 三个臭皮匠. All rights reserved.
//

#import "SearchViewController.h"
#import "NetHandler.h"
#import "AlbumDatailsOfList.h"
#import "AlbumDetailsCell.h"
#import "AlbumOfList.h"
#import "AlbumOfListCell.h"
#import "AlbumDetailsViewController.h"
#import "MainPlayerViewController.h"


#import "AudioPlayer.h"
#import "AudioButton.h"

@interface SearchViewController ()<UISearchBarDelegate, UITableViewDataSource, UITableViewDelegate>

// 表
@property (nonatomic, retain) UITableView *searchTableView;

// 数据数组
@property (nonatomic, retain) NSMutableArray *arr;
// 声音数组
@property (nonatomic, retain) NSMutableArray *soundArr;
// 专辑数组
@property (nonatomic, retain) NSMutableArray *AlbumArr;
// 搜索框
@property (nonatomic, retain) UISearchBar *searchBar;
// 标记显示哪一种cell
@property (nonatomic, assign) NSInteger flag;
// segment
@property (nonatomic, retain) UISegmentedControl *segment;
// 当前请求的是第几页
@property (nonatomic, retain) NSString *page;
// 一共找到多少条记录
@property (nonatomic, assign) NSNumber *numFound;
// 现在是哪个cell
@property (nonatomic, retain) NSString *mark;

@property (nonatomic, retain) NSString *searBarStr;

@property (nonatomic, assign) NSInteger cellTag;


@property (nonatomic, retain)AlbumDetailsCell *cell;

@property (nonatomic, retain)AudioButton *audioBtn;

@property(nonatomic, retain) MainPlayerViewController *mainPlayVC;
@end

@implementation SearchViewController

#pragma mark 初始化
- (instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        self.mark = @"normal";
        self.flag = 2;
        self.page = @"1";
        self.arr = [NSMutableArray array];
        self.soundArr = [NSMutableArray array];
        self.AlbumArr = [NSMutableArray array];
    }
    
    return self;
}

#pragma mark 释放
- (void)dealloc
{
    [_searchTableView release];
    [_searchBar release];
    [super dealloc];
}

#pragma mark 获取网络数据

- (void)handleData
{
    NSString *str = @"http://mobile.ximalaya.com/m/hot_search_keys?device=IPhone";
    [NetHandler getDataWithURL:str completion:^(NSData *data) {
       
        NSDictionary *sourceDic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
        
        [self.arr addObjectsFromArray:[sourceDic objectForKey:@"keys"]];
        
        [self.searchTableView reloadData];
        //self.mark = @"album";
        //self.flag = 0;
    }];
    
    
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self handleData];
    
    self.view.backgroundColor = [UIColor whiteColor];
    self.automaticallyAdjustsScrollViewInsets = YES;
    self.navigationController.navigationBar.translucent = YES;

    self.navigationItem.hidesBackButton = YES;
#pragma mark 设置搜索栏
    
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, 64)];
    view.backgroundColor = [UIColor clearColor];
    //设置搜索栏  固定在导航栏下边
    self.searchBar = [[UISearchBar alloc] initWithFrame:CGRectMake(0, 20, self.view.bounds.size.width - 15, 30)];
    _searchBar.placeholder=@"搜索声音,专辑";
    _searchBar.delegate = self;
    _searchBar.backgroundColor = [UIColor clearColor];
    //是否进行文字纠错  YES. NO;
    _searchBar.autocorrectionType = UITextAutocorrectionTypeNo;
    //单词首字母是否大写  None不大写   Words大写
    //_searchBar.autocapitalizationType = UITextAutocapitalizationTypeNone;
    _searchBar.searchBarStyle = UISearchBarStyleMinimal;
    [_searchBar release];
    
    [view addSubview:self.searchBar];
    self.navigationItem.titleView = view;

    self.segment = [[UISegmentedControl alloc]initWithItems:[NSArray arrayWithObjects:@"专辑",@"声音", nil]];
    self.segment.selectedSegmentIndex = 0;
    self.segment.alpha = 1;
    self.segment.backgroundColor = [UIColor clearColor];
    
    self.segment.frame = CGRectMake(0, 5, self.view.frame.size.width, 30);
    [self.segment addTarget:self action:@selector(changeSegment:) forControlEvents:UIControlEventValueChanged];
    [_segment release];
    
    
#pragma mark 设置tableView
    self.searchTableView = [[UITableView alloc] initWithFrame:CGRectMake(self.view.bounds.origin.x, 0, self.view.bounds.size.width, self.view.bounds.size.height) style:UITableViewStylePlain];
    self.searchTableView.dataSource = self;
    self.searchTableView.delegate = self;
    self.searchTableView.sectionHeaderHeight = 40;
    
    [self.view addSubview:self.searchTableView];
    
    [self.searchTableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"normalReuse"];
    [self.searchTableView registerClass:[AlbumDetailsCell class] forCellReuseIdentifier:@"SoundsReuse"];
    
        [self.searchTableView registerClass:[AlbumOfListCell class] forCellReuseIdentifier:@"AlbumReuse"];
    
    // Do any additional setup after loading the view.
 
}

#pragma mark searchBar的协议方法
- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText
{
    if (self.segment.selectedSegmentIndex == 0) {
        self.flag = 0;
         self.mark = @"album";
    } else {
        
        self.flag = 1;
         self.mark = @"sound";
        
    }
     searchBar.showsCancelButton = YES;
    self.searBarStr = searchText;
    if (self.flag == 1) {
        [self.arr removeAllObjects];
        [self.soundArr removeAllObjects];
        [self getSoundsInfor:searchText];
    } else if (self.flag == 0) {
        
        [self.arr removeAllObjects];
        [self.AlbumArr removeAllObjects];
        [self getAlbumInfor:searchText];
    }
}

#pragma mark 显示离开按钮
- (BOOL)searchBarShouldBeginEditing:(UISearchBar *)searchBar {
    //显示离开按钮
    
    searchBar.showsCancelButton = YES;

    return YES;
}

#pragma mark 点击离开按钮
- (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar
{
    
    [self.navigationController popViewControllerAnimated:YES];
    
}


#pragma mark tableView的协议方法
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
   return self.arr.count;
}


#pragma mark cell
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    if (self.flag == 2) {
        
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"normalReuse"];
        cell.textLabel.text = [self.arr objectAtIndex:indexPath.row];
        return cell;
    } else if (self.flag == 1) {
        
        
        static NSString *str = @"datails";
        
        AlbumDetailsCell *cell = [tableView dequeueReusableCellWithIdentifier:str];
        
        if (cell == nil || self.cellTag != 10000 + indexPath.row) {
            
            cell = [[[AlbumDetailsCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:str] autorelease];
            [cell.audioButton addTarget:self action:@selector(playTheAudio:) forControlEvents:UIControlEventTouchUpInside];
        }
        cell.audioButton.tag = indexPath.row + 10000;
        
        if (self.cellTag == 10000 + indexPath.row) {
            [cell.audioButton removeFromSuperview];
            [cell.contentView addSubview:self.audioBtn];

        }

        AlbumDatailsOfList *datailList = [self.arr objectAtIndex:indexPath.row];
        
   
        
        
        cell.albumDatailsOfList = datailList;
        
        return cell;

    } else if (self.flag == 0){
        
        AlbumOfListCell *cell = [tableView dequeueReusableCellWithIdentifier:@"AlbumReuse"];
        cell.albumList = [self.arr objectAtIndex:indexPath.row];
        return cell;
    }
    
    return nil;
}

#pragma mark Header的title
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
    return [NSString stringWithFormat:@"section:%ld", section];
}

#pragma mark Header的view
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    NSString *sectionTitle = [self tableView:tableView titleForHeaderInSection:section];
    if (sectionTitle == nil) {
        return nil;
    }
    // Create header view and add label as a subview
    UIView *sectionView = [[[UIView alloc] initWithFrame:CGRectMake(0, 0, tableView.bounds.size.width, tableView.bounds.size.height)] autorelease];
    [sectionView setBackgroundColor:[UIColor whiteColor]];
    // sectionView.userInteractionEnabled = YES;
    [sectionView addSubview:self.segment];
    
    return sectionView;
    
}

#pragma mark row的高
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (self.flag == 2) {
        
        return (self.view.bounds.size.height - 64 - 40) / self.arr.count;
        
    } else if (self.flag == 1) {
        
        return 100;
    } else {
        
        return 80;
        
    }
}

#pragma mark 点击cell的方法
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    if ([self.mark isEqualToString:@"normal"]) {
        
        if (self.segment.selectedSegmentIndex == 1) {
            self.mark = @"sound";
            NSString *str = [self.arr objectAtIndex:indexPath.row];
            self.searBarStr = str;
            [self.arr removeAllObjects];
            [self.soundArr removeAllObjects];
            [self.searchTableView reloadData];

            [self getSoundsInfor:str];
            
        } else if (self.segment.selectedSegmentIndex == 0) {
            self.mark = @"album";
            
            NSString *str = [self.arr objectAtIndex:indexPath.row];
            self.searBarStr = str;
            [self.arr removeAllObjects];
            [self.AlbumArr removeAllObjects];
            [self.searchTableView reloadData];

            self.flag = 0;
            [self getAlbumInfor:str];
        }
        
    } else if (self.segment.selectedSegmentIndex == 0) {
        
        AlbumDetailsViewController *albumDetailsVC = [[AlbumDetailsViewController alloc] init];
        albumDetailsVC.albumOfList = [self.arr objectAtIndex:indexPath.row];
        [self.navigationController pushViewController:albumDetailsVC animated:YES];
        [albumDetailsVC release];
        
    } else if (self.segment.selectedSegmentIndex == 1) {
        
        
        self.cell = (AlbumDetailsCell *)[tableView cellForRowAtIndexPath:indexPath];
        
        AlbumDatailsOfList *dataList = [self.arr objectAtIndex:indexPath.row];
        
        _mainPlayVC = [MainPlayerViewController defaultPlayer];
        
        
        _mainPlayVC.albumDatail = dataList;
        _mainPlayVC.trackId =[NSNumber numberWithInteger: [dataList.id integerValue]];
        _mainPlayVC.index = indexPath.row;
        [_mainPlayVC.listArr removeAllObjects];
        [_mainPlayVC.listArr addObjectsFromArray:self.arr];
        _mainPlayVC.navi = self.navigationController;
        _audioPlayer = [AudioPlayer shareInstance];
        // 专辑数组为空
        //_mainPlayVC.listArr = nil;
        
        if (![_audioPlayer.button isEqual:_cell.audioButton]) {
            
            [_audioPlayer stop];
            self.audioBtn = _cell.audioButton;
            
            ;
            _audioPlayer.button = _cell.audioButton;
            self.cellTag = _cell.audioButton.tag;
            _audioPlayer.url = [NSURL URLWithString:dataList.playUrl64];
            [_audioPlayer play];
            
        }
        
        
        // _mainPlayVC.audioButton = _cell.audioButton;
        
        [_mainPlayVC showDetailInformation];
        
//        [self presentViewController:_mainPlayVC animated:YES completion:^{
//            
//            
//        }];
        CATransition *transition = [CATransition animation];
        transition.duration = 0.3f;
        transition.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
        transition.type = @"push";
        transition.subtype = kCATransitionFromTop;
        transition.delegate = self;
        [self.navigationController.view.layer addAnimation:transition forKey:nil];
        [self.navigationController pushViewController:_mainPlayVC animated:NO];
        
    }
    
}
#pragma mark 点击播放的按钮

- (void)playTheAudio:(AudioButton *)button
{
    
    self.audioBtn = button;
    
    self.cellTag = button.tag;
    
    _audioPlayer =  [AudioPlayer shareInstance];
    
    if ([_audioPlayer.button isEqual: button]) {
        
        [_audioPlayer play];
        
    } else {
        
        _mainPlayVC = [MainPlayerViewController defaultPlayer];
        _mainPlayVC.trackId = [NSNumber numberWithFloat:[[[self.arr objectAtIndex:button.tag - 10000 ] id] floatValue]];
        [_mainPlayVC showDetailInformation];
        
        [_audioPlayer stop];
        
        _audioPlayer.button = button;
        
        _audioPlayer.url = [NSURL URLWithString:[[self.arr objectAtIndex:button.tag - 10000] playUrl64] ];
        
        [_audioPlayer play];
    }
    
}


#pragma mark segment的方法

- (void)changeSegment:(UISegmentedControl *)seg
{
    [self.searchBar resignFirstResponder];
    if (seg.selectedSegmentIndex == 0) {
        self.flag = 0;
        if (self.searchBar.text.length != 0) {
            [self.arr removeAllObjects];
            [self.AlbumArr removeAllObjects];
            [self.searchTableView reloadData];

            [self getAlbumInfor:self.searchBar.text];
        } else {
            
            [self.arr removeAllObjects];
            [self.AlbumArr removeAllObjects];
            [self getAlbumInfor:self.searBarStr];
            
        }
    } else if (seg.selectedSegmentIndex == 1) {
        self.flag = 1;
        if (self.searchBar.text.length != 0) {
            
            [self.arr removeAllObjects];
            [self.soundArr removeAllObjects];
            [self.searchTableView reloadData];
            [self getSoundsInfor:self.searchBar.text];
            
        } else {
            
            [self.arr removeAllObjects];
            [self.soundArr removeAllObjects];
            [self getSoundsInfor:self.searchBar.text];
            
        }
        
    }

    
}


#pragma mark 获得声音信息

- (void)getSoundsInfor:(NSString *)str
{
    NSString *strPath = [NSString stringWithFormat:@"http://mobile.ximalaya.com/s/mobile/search?device=iPhone&condition=%@&page=%@&per_page=20&scope=voice", str, self.page];
    [NetHandler getDataWithURL:strPath completion:^(NSData *data) {
        
        NSDictionary *sourceDic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
        
        NSDictionary *responseDic = [sourceDic objectForKey:@"response"];
        
        self.numFound = [responseDic objectForKey:@"numFound"];
        
        NSArray *docsArr = [responseDic objectForKey:@"docs"];
        
        for (NSDictionary *dic in docsArr) {
            
            AlbumDatailsOfList *albumDetailsOflist = [[AlbumDatailsOfList alloc] initWithDictionary:dic];
            
            [self.soundArr addObject:albumDetailsOflist];
            [albumDetailsOflist release];
        }
        [self.arr removeAllObjects];
        [self.arr addObjectsFromArray:self.soundArr];
        [self.searchTableView reloadData];
    }];
}

#pragma mark 获得专辑信息

- (void)getAlbumInfor:(NSString *)str
{
    NSString *strPath = [NSString stringWithFormat:@"http://mobile.ximalaya.com/s/mobile/search?device=iPhone&condition=%@&page=%@&per_page=20&scope=album", str, self.page];
    [NetHandler getDataWithURL:strPath completion:^(NSData *data) {
        
        NSDictionary *sourceDic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
        
        NSDictionary *responseDic = [sourceDic objectForKey:@"response"];
        
        self.numFound = [responseDic objectForKey:@"numFound"];
        
        NSArray *docsArr = [responseDic objectForKey:@"docs"];
        
        for (NSDictionary *dic in docsArr) {

            AlbumOfList *albumOflist = [[AlbumOfList alloc] initWithDictionary:dic];
            if (![[albumOflist.tracks description] isEqualToString:@"0"]) {
                  [self.AlbumArr addObject:albumOflist];
            }
          

            [AlbumOfList release];
        }
        [self.arr removeAllObjects];
        [self.arr addObjectsFromArray:self.AlbumArr];

        [self.searchTableView reloadData];
    }];
 
}



- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
